<template>
  <basic-dialog :visible="show"
                title="验证身份信息"
                :isShowInnerLoading="isShowInnerLoading"
                min-width="400px"
                isShowBasicFooter
                @close="onReset"
                @submit="onSubmit"
  >
    <q-form greedy
            ref="myForm"
            class="dialog-content form-inline block margin-t-20">
      <div>
        <yz-input v-model="queryParams.phone"
                  inputType="input"
                  is-disable
                  :rules="[0]"
                  title="手机号"
        />
        <q-input v-model="queryParams.code" autofocus outlined dense
                 :rules="[val => /^\d{6}$/.test(val) || '请输入正确验证码']">
          <template v-slot:before>
            <label class="text-right name"><span class="text-red">*</span> 验证码:</label>
          </template>
          <template v-slot:append>
            <q-btn :disable="codeTimer !== null" flat rounded color="primary" :label="codeMessage" @click="getCode" />
          </template>
        </q-input>
      </div>
    </q-form>
  </basic-dialog>
</template>

<script>
import { mapGetters } from 'vuex'
import { getOptToken, getSmsCode } from '../../../../boot/home/home'

export default {
  name: 'VerifyInfoDialog',
  data () {
    return {
      isShowInnerLoading: false,
      codeMessage: '获取验证码',
      codeTimer: null,
      codeTime: 90,
      queryParams: {
        phone: '',
        code: ''
      }
    }
  },
  computed: {
    ...mapGetters({
      'userInfo': 'userInfo',
      'userDetail': 'userDetail'
    })
  },
  props: {
    show: Boolean
  },
  watch: {
    show () {
      // 重置验证码
      this.queryParams.phone = this.userDetail.phone
      this.codeTimer = null
      this.codeMessage = `获取验证码`
      this.codeTime = 90
    }
  },
  methods: {
    // 提交验证码是否正确
    onSubmit () {
      this.$refs.myForm.validate(true).then(result => {
        if (result) {
          getOptToken(this.queryParams.phone, this.queryParams.code).then(res => {
            if (res.code) {
              this.$emit('success')
            }
          })
        }
      })
    },
    // 重置
    onReset () {
      Object.assign(this.queryParams, this.$options.data.call(this).queryParams)
      this.$emit('close')
    },
    // 获取验证码
    getCode () {
      this.codeTimer = setInterval(() => {
        if (this.codeTime === 0) {
          clearInterval(this.codeTimer)
          this.codeTimer = null
          this.codeMessage = `重新获取`
          this.codeTime = 90
          return
        }
        this.codeTime--
        this.codeMessage = `重新获取(${this.codeTime})`
      }, 1000)
      const params = {
        phone: this.queryParams.phone,
        type: 'EXTERNAL'
      }
      getSmsCode(params)
    }
  }
}
</script>

<style scoped lang="scss">
.code-btn{
  font-size: 14px;
  cursor: pointer;
  color: #5f77fd;
}
</style>
